package com.tao.service.impl.Mq;


import com.tao.factorys.MiaoshaFactory;
import com.tao.factorys.SubmittableFactory;
import com.tao.pojo.Miaosha;
import com.tao.pojo.Submittable;
import com.tao.service.MiaoshaService;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;
//MiaoshaReceiveService
//MiaoshaSendService

/*
秒杀 点击后 发送Mq中，方法如下
 */
@Service
public class MiaoshaSendService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Resource
    SubmittableFactory submittableFactory;

    @Resource
    MiaoshaFactory miaoshaFactory;
    // 1: 定义交换机
    private String exchangeName = "miaoshaSyt";
    // 2: 路由key
    private String routeKey0 = "topic.miaoshaSyt.id";

    /*
    核心句子
    rabbitTemplate.convertAndSend(exchangeName, routeKey0, orderNumer);
    发送后没有这些也没关系，消费者可以通过注解创建
     */

    public void makeOrder() {
        // 1： 模拟用户下单
        String orderNumer = UUID.randomUUID().toString();
        // 2: 根据商品id productId 去查询商品的库存
        // int numstore = productSerivce.getProductNum(productId);
        // 3:判断库存是否充足
        // if(num >  numstore ){ return  "商品库存不足..."; }
        // 4: 下单逻辑
        // orderService.saveOrder(order);
        // 5: 下单成功要扣减库存
        // 6: 下单完成以后
//        System.out.println("用户 " + userId + ",订单编号是：" + orderNumer+";key："+routeKey0);
        // 发送订单信息给RabbitMQ Deract
        rabbitTemplate.convertAndSend(exchangeName, routeKey0, orderNumer);
    }

    //mq 请求测试，qid 随机，aid 默认666
    public void sendTest(){
        String orderNumer = UUID.randomUUID().toString();
        Miaosha miaosha=miaoshaFactory.getMiaosha(orderNumer);
        routeKey0="topic.miaoshaSyt.id";
//        System.out.println("rabbitmq:coding:"+miaosha.toString());
        rabbitTemplate.convertAndSend(exchangeName, routeKey0, miaosha);
    }


    @Autowired
    MiaoshaService miaoshaService;

    // 根据 qid  aid 来发送秒杀订单；消费者收到之后 让redies 库存-1  提交submitTable 数据库
    @CacheEvict(value = "miaosha::count",key = "'getMiaoshaValues'")
    public String SubmitMiaosha(Long qid,Long aid){
//        获取秒杀数据，查看是否还有库存
        int miaoshaSum = miaoshaService.getMiaoshaSum(aid);
        if (miaoshaSum<=0){
            return "none";
        }

        //订单提交  submitTable 到rabbitMq
        Submittable submittable = submittableFactory.getSubmittable(qid, aid);
        String routeKey="topic.submitTable.miaosha";
        String eName="submitTable.miaosha";
        rabbitTemplate.convertAndSend(eName, routeKey, submittable);
        return "success";
    }



}